<script setup>
import { computed, nextTick, ref, watch } from 'vue';

import { checkPoint, batchInputPoint } from "@/api/device";

const visible = defineModel("visible")

const props = defineProps({
  data: {
    type: Array,
    default: []
  }
})

const emits = defineEmits(["update"])

const columns = [
  { prop: "group", label: "分组" },
  { prop: "name", label: "代号" },
  { prop: "func", label: "功能码" },
  { prop: "addr", label: "地址" },
  { prop: "desc", label: "描述" },
]

const checkedData = ref([])

watch(visible, val => {
  if (val) {
    nextTick(() => {
      checkPoint(props.data).then(res => {
        if (res.code === 200) {
          checkedData.value = res.data
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
        ElMessage.error("网络异常，请稍后重试")
      })
    })
  }
})

function cellClassName(row, key) {
  let className = ""
  if (row[key].level == 1) className = "warn-level"
  else if (row[key].level == 2) className = "err-level"
  return className
}

// 对单元格进行标注，用于合并相同单元格
const cellSpans = computed(() => {
  const result = {}
  checkedData.value.forEach(item => {
    const spanMap = {}
    for (let i = 0; i < item.points.length; i++) {
      const point = item.points[i];
      if (!spanMap[point.group.value]) spanMap[point.group.value] = [i, 1]
      else spanMap[point.group.value][1] += 1
    }
    result[item.deviceNo.value] = spanMap
  });
  return result
})

// 合并组名相同的单元格
function mergeCellSpan(deviceNo, { row, column, rowIndex, columnIndex }) {
  const cellSpan = cellSpans.value[deviceNo]
  if (cellSpan && columnIndex == 0) {
    const spanItem = cellSpan[row[column.property].value]
    if (rowIndex === spanItem[0]) {
      return [spanItem[1], 1]
    } else {
      return [0, 0]
    }
  }
}

// 判断是否存在非法点位
const hasErrItem = computed(() => {
  let result = false
  for (let i = 0; i < checkedData.value.length; i++) {
    const item = checkedData.value[i];
    if (item.deviceNo.level > 0) {
      result = true
      return result
    }
    for (let j = 0; j < item.points.length; j++) {
      const p = item.points[j]
      for (const key in p) {
        if (p[key].level > 0) {
          result = true
          return result
        }
      }
    }
  }
  return result
})

const updateVisible = ref(false)
const updateResult = ref()
function submit() {
  batchInputPoint(props.data).then(res => {
    if (res.code === 200) {
      emits("update")
      ElMessage.success("导入完成，请查看导入数据报告")
      updateResult.value = res.data
      visible.value = false
      updateVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
</script>

<template>
  <el-dialog v-model="visible" title="点位预览" class="dialog-box">
    <div v-if="hasErrItem" style="margin-top: -24px;">
      <div>请谨慎检查以下数据：</div>
      <div>
        <span class="err-text">红色数据</span>
        将无法被正常导入
      </div>
      <div style="margin-bottom: 12px;">
        <span class="warn-text">黄色数据</span>
        可能在导入过程中产生未知的问题
      </div>
    </div>
    <el-tabs type="border-card" tab-position="bottom">
      <el-tab-pane 
        v-for="data in checkedData"
      >
        <template #label>
          <el-tooltip 
            v-if="data.deviceNo.level > 0"
            effect="dark"
            :content="data.deviceNo.tip"
          ><div :class="{
            'warn-text': data.deviceNo.level == 1,
            'err-text': data.deviceNo.level == 2,
          }">{{ data.deviceNo.value }}</div></el-tooltip>
          <span v-else>{{ data.deviceNo.value }}</span>
        </template>
        <el-table 
          border
          :data="data.points" 
          height="480"
          :span-method="(params) => mergeCellSpan(data.deviceNo.value, params)"
          :cell-class-name="({ row, column }) => cellClassName(row, column.property)"
        >
          <el-table-column 
            v-for="item in columns" 
            :label="item.label" :prop="item.prop"
          >
            <template #default="{ row }">
              <el-tooltip 
                v-if="row[item.prop].level > 0"
                effect="dark"
                :content="row[item.prop].tip"
              ><div :class="{'cell-class': true, 'text-center': !row[item.prop].value}">
                {{ row[item.prop].value ?? '空数据' }}
              </div></el-tooltip>
              <span v-else>{{ row[item.prop].value }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div class="btn-group">
      <div v-if="hasErrItem">
        <el-button type="danger" @click="submit()">忽略警告，继续导入</el-button>
        <el-button @click="visible = false">再检查一下</el-button>
      </div>
      <div v-else>
        <el-button type="primary" @click="submit()">继续导入</el-button>
        <el-button>取消</el-button>
      </div>
    </div>
  </el-dialog>
  <el-dialog v-model="updateVisible" title="导入数据报告">
    <div style="margin-top: -24px; margin-bottom: 12px;">
      <div>导入点总数：{{ updateResult.count }}个，
        <span class="success-text">导入成功：</span>{{ updateResult.successCount }}个， 
        <span class="err-text">导入失败：</span>{{ updateResult.failCount }}个
      </div>
    </div>
    <el-tabs type="border-card">
      <el-tab-pane label="导入失败点位">
        <el-table :data="updateResult.failList" height="480" empty-text="无导入失败的点位">
          <el-table-column prop="deviceNo" label="所属设备" />
          <el-table-column prop="group" label="分组" />
          <el-table-column prop="name" label="代号" />
          <el-table-column prop="func" label="功能码" />
          <el-table-column prop="addr" label="地址" />
          <el-table-column prop="desc" label="描述" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="导入成功点位">
        <el-table :data="updateResult.successList" height="480" empty-text="无导入成功的点位">
          <el-table-column prop="deviceNo" label="所属设备" />
          <el-table-column prop="group" label="分组" />
          <el-table-column prop="name" label="代号" />
          <el-table-column prop="func" label="功能码" />
          <el-table-column prop="addr" label="地址" />
          <el-table-column prop="desc" label="描述" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.warn-level) {
  background-color: var(--el-color-warning-light-5)!important;
}
:deep(.err-level) {
  background-color: var(--el-color-danger-light-3)!important;
}
:deep(.warn-level):hover {
  background-color: var(--el-color-warning)!important;
}
:deep(.err-level):hover {
  background-color: var(--el-color-danger)!important;
}
.el-table tbody tr { 
    pointer-events:none; 
}
.cell-class {
  width: 100%;
  height: 100%;
}
.success-text {
  color: var(--el-color-success);
  font-weight: 700;
}
.warn-text {
  color: var(--el-color-warning);
  font-weight: 700;
}
.err-text {
  color: var(--el-color-danger);
  font-weight: 700;
}
.btn-group {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
.text-center {
  text-align: center;
  color: white;
}
</style>